<?php

namespace app\api\controller;

use app\admin\model\Operator;
use app\admin\model\Member;
use app\admin\model\Povertymember;
use app\admin\model\Povertyparty;
use app\admin\model\Povertyproject;
use app\admin\model\Povertywork;
use app\admin\model\Articlelike;
use app\admin\model\Ethnic;
use app\admin\model\Image;

class Poverty extends BaseController
{

    /**
     * 扶贫项目列表
     */
    public function povertyproject() {
        $param = self::getHttpParam();
        $start = 0;
        $length = 10;

        if (empty($param->townId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'townId 不能为空');
        }
        if (!empty($param->start)) {
            $start = $param->start;
        }
        if (!empty($param->length)) {
            $length = $param->length;
        }

        $where = [
            'a.townId' => $param->townId,
            'a.isDelete' => 2
        ];
        if(!empty($param->villageId)) {
            $where['a.villageId'] = $param->villageId;
        }
        if(!empty($param->type) && $param->type != 0) {
            $where['a.typeId'] = $param->type;
        } else {
            // 默认是首页推荐
            $where['a.isRecommend'] = 1;
        }

        $model = new Povertyproject();
        $fields = 'a.id, a.imgUrl, a.title, a.status, a.type, a.cityId, a.xianId, a.townId, a.villageId, b.name as povertyName';
        $list = $model->alias('a')->where($where)->join('member b','a.povertymemberId = b.id')->field($fields)->order('a.createDate DESC')->limit($start, $length)->select();
        $total = $model->alias('a')->where($where)->join('member b','a.povertymemberId = b.id')->count();

        if (empty($list)) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '未查到帮扶项目信息');
        }

        foreach ($list as $item) {
            // 所在地
            $item['area'] = getArea($item, '');
        }

        return showTotal(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $list, $total);
    }

    /**
     * 扶贫项目详情
     */
    public function povertyprojectDetail() {
        $param = self::getHttpParam();

        $id = $param->id;
        $where = [
            'a.id' => $id,
            'a.isDelete' => 2
        ];

        $model = new Povertyproject();
        $item = $model->alias('a')->where($where)->join('member m','a.povertymemberId = m.id')->field('a.*, m.name povertyName')->find()->toArray();
        if(empty($item) || !$item) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '未查到详情');
        }
        // 帮扶人
        $aidingInfo = Member::where(['id' => $item['aidingId']])->field('name')->find();
        $item['aidingName'] = $aidingInfo['name'];
        // 扶贫进展
        $details = \app\admin\model\Povertyprojectdetail::where(['projectId' => $id, 'isDelete' => 2])->select();
        foreach ($details as $key => $val) {
            $details[$key]['content'] = $item['type'] == 1 ? '捐助'.$val['donateContent'].$val['donateNum'].'件' : '捐助金额'.$val['donateMoney']/100 . '元' ;
        }
        $item['details'] = $details;
        // 图集
        $imagesList = Image::where(['relatedId' => $id, 'tag' => 'imglist'])->field('imgUrl')->order('sorting ASC')->select();
        $item['imagesList'] = $imagesList;

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $item);
    }

    /**
     * 帮扶工作列表
     */
    public function povertywork() {
        $param = self::getHttpParam();
        $start = 0;
        $length = 10;

        if (empty($param->townId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'townId不能为空');
        }
        if (empty($param->userId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'userId 不能为空');
        }
        if (!empty($param->start)) {
            $start = $param->start;
        }
        if (!empty($param->length)) {
            $length = $param->length;
        }

        $where = [
            'a.townId' => $param->townId,
            'a.isDelete' => 2
        ];
        if(!empty($param->villageId)) {
            $where['a.villageId'] = $param->villageId;
        }

        $model = new Povertywork();
        $fields = 'a.id, a.povertymemberId, a.aidingId, a.content, a.cityId, a.xianId, a.townId, a.villageId, b.name as povertyName';
        $list = $model->alias('a')->where($where)->join('member b','a.povertymemberId = b.id')->field($fields)->order('a.createDate DESC')->limit($start, $length)->select();
        $total = $model->alias('a')->where($where)->join('member b','a.povertymemberId = b.id')->count();

        if (empty($list)) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '未查到帮扶工作信息');
        }
        foreach ($list as $item) {
            // 扶贫干部
            $item['aidingName'] = Member::where('id', $item['aidingId'])->value('name');

            // 图集
            $imagesList = Image::where(['relatedId' => $item['id'], 'tag' => 'imglist'])->field('imgUrl')->order('sorting ASC')->select();
            $item['imagesList'] = $imagesList;
        }

        return showTotal(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $list, $total);
    }


    // 贫困户各类人数查询
    public function outpovertyCount() {
        $param = self::getHttpParam();
        if (empty($param->villageId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'villageId不能为空');
        }

        $poverty1 = povertymember::where(['outpoverty'=>1,'villageId'=>$param->villageId])->count();   //未脱贫
        $poverty2 = povertymember::where(['outpoverty'=>2,'villageId'=>$param->villageId])->count();   //已脱贫
        $poverty3 = povertymember::where(['outpoverty'=>3,'villageId'=>$param->villageId])->count();   //返贫

        $data = [
            'poverty' => $poverty1,
            'outPoverty' => $poverty2,
            'againPoverty' => $poverty3,
        ];

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $data);
    }

    // 贫困户列表
    public function povertymember() {
        $param = self::getHttpParam();
        $start = 0;
        $length = 20;

        if (empty($param->villageId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'villageId不能为空');
        }
        if (!empty($param->start)) {
            $start = $param->start;
        }
        if (!empty($param->length)) {
            $length = $param->length;
        }

        $where = [
            'villageId' => $param->villageId
        ];
        if(!empty($param->memberId)) {  //查询某一帮扶干部下的贫困户
            $where['aidingId'] = $param->memberId;
        }
        if(!empty($param->status)) {  //1：未脱贫 2：已脱贫 3：返贫
            $where['outpoverty'] = $param->status;
        }

        $ethnic = Ethnic::order('sorting ASC')->select();  //民族
        $ethnicMap = [];
        foreach ($ethnic as $e) {
            $ethnicMap[$e['id']] = $e['name'];
        }

        $operatorMap = Operator::getAllOperatorJob($param->villageId);

        $list =  Povertymember::where($where)->limit($start, $length)->select();
        $total = Povertymember::where($where)->count();

        if (empty($list)) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '未查到贫苦户信息');
        }
        foreach ($list as $key => $val) {
            $list[$key]['member'] = $val->member;   //贫苦户基本信息
            $list[$key]['member']['ethnicId'] = $ethnicMap[$list[$key]['member']['ethnicId']];
            $list[$key]['memberaid'] = $val->memberaid;  //帮扶人信息
            $list[$key]['memberaid']['job'] = isset($operatorMap[$list[$key]['memberaid']['id']]) ? $operatorMap[$list[$key]['memberaid']['id']][0] : '';
        }

        return showTotal(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $list, $total);
    }

    // 贫困户详情
    public function povertymemberDetail() {
        $param = self::getHttpParam();
        if(empty($param->id)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'id不能为空');
        }

        $item = Povertymember::where('id',$param->id)->find();
        if(empty($item)) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '未查到贫苦户信息');
        }
        $item['aidingPlan'] = viewAidingplan($item['aidingPlan']);
        $item['member'] = $item->member;
        $item['memberaid'] = $item->memberaid;
        $jobRow = operator::alias('a')
            ->where(['a.memberId' => $item['memberaid']['id']])
            ->join('operatorjob c','a.id = c.operatorId')
            ->join('organizationjob d','c.jobId = d.id')
            ->field('a.*, d.name')
            ->order('d.sorting,createDate DESC')
            ->find();
        $ethnic = Ethnic::get($item['member']['ethnicId']);
        $item['member']['ethnicId'] = $ethnic['name'];
        $item['memberaid']['job'] = $jobRow ? $jobRow['name'] : '';

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $item);
    }

    //扶贫干部列表
    public function partyList() {
        $param = self::getHttpParam();
        if (empty($param->villageId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'villageId不能为空');
        }

        $list =  Povertyparty::where(['villageId'=>$param->villageId])->select();
        if (empty($list)) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '未查到贫苦户信息');
        }
        $operatorMap = Operator::getAllOperatorJob($param->villageId);
        foreach ($list as $key => $val) {
            $list[$key]['member'] = $val->member;
            $list[$key]['member']['job'] = isset($operatorMap[$val['memberId']]) ? $operatorMap[$val['memberId']][0] : '';
        }

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $list);
    }

    // 获取扶贫列表
    protected function getPovertys($where, $start, $length)
    {
        $where['a.isDelete'] = 2;
        $model = new \app\admin\model\Povertyproject();
        $fields = 'a.*';
        $order = 'createDate DESC';
        $result = $model->alias('a')->where($where)->join('member m','a.memberId = m.id')->field($fields)->order($order)->limit($start, $length)->select();
        if(!$result){
            return [];
        }

        foreach ($result as &$item) {
            // 帮扶人 // TODO 不能用 Povertyproject 表里的 aidingId（帮扶人）字段，因为贫困户的 aidingId 会发生改变
            $aidingId = Povertymember::where(['memberId' => $item->memberId])->value('aidingId');
            if($aidingId){
                $aidingInfo = Member::where(['id' => $aidingId])->field('id, name, avatar, job')->find();
                $item->memberaid = $aidingInfo;
            }
        }

        return $result;
    }
}